﻿using System;
using System.Collections.Generic;

using RexToy.IoC;
using RexToy.UI.WinForm;
using RexToy.UI.WinForm.Pmlx;
using RexToy.UI.WinForm.ViewModel;

using Studio.Model;

namespace Studio.ViewModel
{
    public class TemplateEditVM : ViewModelBase
    {
        private TemplateRenderModel _model = new TemplateRenderModel();

        public string EditText
        {
            get { return _model.Input; }
            set
            {
                if (_model.Input == value)
                    return;

                _model.Input = value;

                this.OnPropertyChange<TemplateRenderModel>(m => m.Input);
                CommandBindRegistry.Instance().RequeryCanExecute();//Extend: error might occur, will impact the status of detail bar.
            }
        }

        public string ResultText
        {
            get { return _model.Output; }
        }

        public Exception Error
        {
            get { return _model.Error; }
        }

        private IUICommand _detailCmd;
        public IUICommand DetailCmd
        {
            get
            {
                if (_detailCmd == null)
                    _detailCmd = new ActionCommand(() => DetailAction(), () => this.OnDetailCanExecute());
                return _detailCmd;
            }
        }

        private bool OnDetailCanExecute()
        {
            return _model.Error != null;
        }

        private void DetailAction()
        {
            var arg = new BroadcastEventArgs();
            arg.Payload = _model.Error;
            EventBroadcaster.Instance().Publish(Constants.Broadcast_Template_Err, this, arg);
        }

        public void SetDbModel(IDatabaseModel model)
        {
            _model.AssignContext(model);
            this.OnPropertyChange<TemplateEditVM>(vm => vm.ResultText);
            this.OnPropertyChange<TemplateEditVM>(vm => vm.Error);
        }
    }
}
